import {
    get_show,
    showMessage,
    sendMessage,
    pushMessage_ly,
    getLikeStatus,
    deleteMessage
} from "../../api/shool/get_score.js";
import util from "../../utils/util.js";
import {
    wx_login
} from "../../api/login/login_user.js";
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp()
Page({
    
    /**
     * 页面的初始数据
     */
    data: {
        is_load: false,
        wx_info: wx.getStorageSync('wx_user_info'),
        type: 'NEW',
        w: 0,
        fileList: [{
                url: 'https://img.yzcdn.cn/vant/leaf.jpg',
                status: 'uploading',
                message: '上传中',
            }

        ],

        if_dianzhan: false,
        pl_data: [],
        if_pl_open: 'false',
        if_pl: true,
        title: ''
    },
    //登录
    login: function () {
        wx.login({
            success(res) {

                wx_login({
                    code: res.code,
                }).then(res => {
                    if (res.data.statusCode == 200) {
                        //存入用户openid到缓存
                        wx.setStorageSync('openid', res.data.data.openid)
                    }

                })
            }
        })


    },

    //删除留言
    deleteMessage: function (e) {

        // this.setData({
        //     delete_is: true
        // })
        let openid = wx.getStorageSync('openid')
        let index = e.currentTarget.dataset.index_1
        let web_user = wx.getStorageSync('user')
        if (openid == e.currentTarget.dataset.id.retweets || web_user.type == 1) {
            Dialog.confirm({
                    title: '提示',
                    message: '确定要删除您的这条留言吗？',
                })
                .then(() => {

                    deleteMessage({
                        openId: wx.getStorageSync('openid'),
                        leaveMessageId: e.currentTarget.dataset.id.id
                    }).then(res => {
                        if (res.statusCode == 200) {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 1000
                            })
                            //删除列表
                            this.data.pl_data.splice(index, 1)
                            this.setData({
                                pl_data: this.data.pl_data
                            })
                        } else {
                            wx.showToast({
                                title: '删除失败',
                                icon: 'none',
                                duration: 1000
                            })

                            this.data.pl_data.splice(index, 1)
                            this.setData({
                                pl_data: this.data.pl_data
                            })
                        }

                    })
                })
                .catch(() => {
                    // on cancel
                });

        }





    },

    deleteMessage_off() {
        this.setState({
            delete_is: false
        })
    },

    //发送评论
    send_pl: function (e) {

        if (e.detail.type == '1') {
            this.setData({

                if_pl_open: 'false'
            })
            wx.requestSubscribeMessage({
                tmplIds: ['A2xUwOpJv6EJWXd9alXNG964WlB7IMrVAT9kY9oc_M8'],
                success(res) {

                }
            })
            pushMessage_ly(e.detail).then(res => {

                if (res.data.statusCode == 200) {
                    this.data.pl_data = []
                    this.showMessage(1)
                    //信息提示留言成功
                    wx.showToast({
                        title: '留言成功',
                        icon: 'success',
                        duration: 2000
                    })

                } else {
                    wx.showToast({
                        title: '留言失败',
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
            let data = {
                access_token: "accwss_token",
                touser: 'ozQHO5QsL4mKbUUHztD2PDUwaCbY',
                template_id: "A2xUwOpJv6EJWXd9alXNG964WlB7IMrVAT9kY9oc_M8",
                page: "/pages/index/index",
                miniprogram_state: "formal",
                lang: "zh_CN",
                data: {
                    name1: {
                        value: this.data.wx_info.nickName
                    },
                    thing2: {
                        value: "FFLOVE"
                    },
                    thing3: {
                        value: '在平台发布了留言'
                    },
                    date4: {
                        //当前时间
                        value: util.formatTime(new Date())

                    }
                }
            }


            this.app.send_message(data)
        }












    },
    //打开评论
    open_pl() {

        if (!wx.getStorageSync('openid')) {
            this.login()
        }

        if (!wx.getStorageSync('wx_user_info')) {
            this.get_wx_info()
        }

        this.setData({
            if_pl_open: 'true'
        })
    },

    off_pl() {
        this.setData({
            if_pl_open: 'false'

        })
    },
    //防抖
    debounce(fn, delay) {
        let timer = null;
        return function () {
            let context = this;
            let args = arguments;
            if (timer) {
                clearTimeout(timer);
                context.setData({
                    if_pl: true
                })
            }
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        }
    },




    //页面滚动
    touchStart(e) {

        //添加定时器
        this.data.timer = setTimeout(() => {
            this.setData({
                if_pl: false
            })
        }, 80);



    },
    //页面停止滚动

    touchEnd() {
        this.setData({
            if_pl: true
        })
        clearTimeout(this.data.timer);


    },

    get_wx_info() {
        wx.getUserProfile({
            desc: '用于显示评论信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {

                //存入用户信息到缓存
                wx.setStorageSync('wx_user_info', res.userInfo)

            }
        })

    },
    //点击关闭遮罩层
    onClickHide() {
        this.setData({
            if_pl_open: "false",
        })
    },

    //点赞/踩
    dianzhan(e) {


        let {
            value,
            type,
            index
        } = e.currentTarget.dataset

        let messtext = null //推送消息类型

        if (index == 'true') {
            if (value.love_type) { //取消点赞
                this.data.pl_data[type].ip--
                this.app.dianzan({
                    "openId": wx.getStorageSync('openid'),
                    "type": "0",
                    "typeMessageId": value.id,
                    "upOrDown": true
                })
            } else if (!value.love_type) {
                wx.vibrateShort({
                    type: 'heavy',
                    success: res => {
                        console.log(res)
                    }
                })
                this.data.pl_data[type].ip++
                messtext = '点赞了你的留言',
                    this.app.dianzan({
                        "openId": wx.getStorageSync('openid'),
                        "type": "0",
                        "typeMessageId": value.id,
                        "upOrDown": true
                    })

                let data = {
                    access_token: "accwss_token",
                    touser: value.retweets,
                    template_id: "A2xUwOpJv6EJWXd9alXNG964WlB7IMrVAT9kY9oc_M8",
                    page: "/pages/index/index",
                    miniprogram_state: "formal",
                    lang: "zh_CN",
                    data: {
                        name1: {
                            value: this.data.wx_info.nickName
                        },
                        thing2: {
                            value: "FFLOVE"
                        },
                        thing3: {
                            value: messtext
                        },
                        date4: {
                            //当前时间
                            value: util.formatTime(new Date())

                        }
                    }
                }

                if (value.retweets != wx.getStorageSync('openid')) {
                    this.app.send_message(data)
                }



            }

            this.data.pl_data[type].love_type = !this.data.pl_data[type].love_type
            this.data.pl_data[type].love_type ? this.data.pl_data[type].unlove_type = false : ''

        } else {
            if (value.unlove_type) {
                this.app.dianzan({
                    "openId": wx.getStorageSync('openid'),
                    "type": "0",
                    "typeMessageId": value.id,
                    "upOrDown": false
                })
            } else if (!value.unlove_type) {
                if (this.data.pl_data[type].love_type) {
                    this.data.pl_data[type].ip--
                }

                this.app.dianzan({
                    "openId": wx.getStorageSync('openid'),
                    "type": "0",
                    "typeMessageId": value.id,
                    "upOrDown": false
                })
            }
            this.data.pl_data[type].unlove_type = !this.data.pl_data[type].unlove_type
            this.data.pl_data[type].unlove_type ? this.data.pl_data[type].love_type = false : ''
        }






        if (!wx.getStorageSync('openid')) {
            this.login()
        }

        if (!wx.getStorageSync('wx_user_info')) {
            this.get_wx_info()
        }

        //推送消息


        this.setData({
            pl_data: this.data.pl_data
        })
    },

    //获取点赞状态
    async get_dianzan_status(id) {

        let type = await getLikeStatus({
            "openId": wx.getStorageSync('openid'),
            "type": "0",
            "typeMessageId": [id]
        })

        return type
    },
    //点击跳转
    tiaozhuan(e) {
        wx.navigateTo({
            url: '/pages/liuyan_xq/liuyan_xq?list=' +encodeURIComponent(JSON.stringify(e.currentTarget.dataset.list)) 
        })
    },



    punlun(e) {

        if (!wx.getStorageSync('openid')) {
            this.login()
        }

        if (!wx.getStorageSync('wx_user_info')) {
            this.get_wx_info()
        }
        wx.requestSubscribeMessage({
            tmplIds: ['A2xUwOpJv6EJWXd9alXNG964WlB7IMrVAT9kY9oc_M8'],
            success(res) {

            }
        })


        wx.navigateTo({
            url: '/pages/liuyan_xq/liuyan_xq?list=' + JSON.stringify(e.currentTarget.dataset.list) + '&id=1514174705077338112' + '&index=' + e.currentTarget.dataset.index
        })
    },
    tou_type() {

        this.data.page = 1
        this.data.type = this.data.type == 'NEW' ? 'HOT' : 'NEW'
        this.setData({
            type: this.data.type,
            w: this.data.w == '0' ? '70' : '0',
        })
        this.data.pl_data = []
        this.showMessage(1)

    },

    //预览图片
    tab(e) {


        let url = e.currentTarget.dataset.url.url
        let arr = []
        arr.push(url)


        wx.previewImage({
            current: url,
            urls: arr
        })
    },
    //去掉相同对象
    deteleObject(obj) {
        var uniques = [];
        var stringify = {};
        for (var i = 0; i < obj.length; i++) {
            var keys = Object.keys(obj[i]);
            keys.sort(function (a, b) {
                return (Number(a) - Number(b));
            });
            var str = '';
            for (var j = 0; j < keys.length; j++) {
                str += JSON.stringify(keys[j]);
                str += JSON.stringify(obj[i][keys[j]]);
            }
            if (!stringify.hasOwnProperty(str)) {
                uniques.push(obj[i]);
                stringify[str] = true;
            }
        }
        uniques = uniques;
        return uniques;
    },

    //获取留言列表
    async showMessage(page) {
        await showMessage({
            "page": page,
            "pageSize": 20,
            "byType": this.data.type == 'HOT' ? '1' : '0',
        }).then(res => {

            if (res.statusCode == 200) {



                this.data.total = res.data.data.total
                res.data.data.list.forEach(async (item) => {
                    if (item.images[0].url == null) {
                        item.images = []
                    }
                    let if_love = await this.get_dianzan_status(item.id)
                    console.log(if_love.data.data[0])
                    let type = if_love.data.data[0]


                    // type = res.data.data[0]
                    if (type == 'null') {
                        item.love_type = false
                        item.unlove_type = false
                    } else if (type == 'false') {
                        item.love_type = false
                        item.unlove_type = true
                    } else {
                        item.love_type = true
                        item.unlove_type = false
                    }






                    item.content = JSON.parse(item.content)
                    //时间格式化为年月日


                    item.createTime = util.formatTime_1(new Date(item.createTime))
                })



                res.data.data.list.forEach(item => {
                    this.data.pl_data.push(item)
                })


                // this.data.page++



                setTimeout(() => {
                    this.setData({
                        pl_data: this.deteleObject(this.data.pl_data),
                        num: res.data.data.total
                    })


                }, 700)
                setTimeout(() => {
                    if (this.data.request_type == 1) {
                        Toast('刷新成功~');
                    }
                    this.data.request_type = 0
                }, 1000)


            } else {
                //消息提示
                wx.showToast({
                    title: '获取评论失败',
                    icon: 'none',
                    duration: 1000
                })
            }
        }).catch(err => {

        })
    },



    //上拉加载
    async onReachBottom() {
        //上拉加载
        if (this.data.total > this.data.pl_data.length) {
            this.data.page++
            await this.showMessage(this.data.page)
        } else {
            wx.showToast({
                title: '没有更多了',
                icon: 'none',
                duration: 1000
            })
            this.setData({
                is_load: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        this.data.pl_data = []
        this.data.page = 1
        // this.showMessage(this.data.page)
        this.app = getApp()




    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {



    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        //获取微信用户信息
       await get_show().then(res => {
            // this.data.type_1= res.data
            if (res.data.password == app.getVersion()) {
                this.data.type_1 = res.data.stuNumber
                this.data.title = res.data.name
            } else {
                this.data.type_1 = 'false'
            }

            this.setData({
                type_1: this.data.type_1,
                title: this.data.title
            })

        })
        this.showMessage(1)


        this.app.slideupshow(this, 'slide_up1', -200, 1)

        setTimeout(function () {
            this.app.slideupshow(this, 'slide_up2', 210, 1)
            //   this.app.sliderightshow(this, 'show_anim',0,200)
        }.bind(this), 200);





    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

        //你可以看到，动画参数的200,0与渐入时的-200,1刚好是相反的，其实也就做到了页面还原的作用，使页面重新打开时重新展示动画
        this.app.slideupshow(this, 'slide_up1', 200, 0)
        //延时展现容器2，做到瀑布流的效果，见上面预览图
        setTimeout(function () {
            this.app.slideupshow(this, 'slide_up2', 200, 0)

        }.bind(this), 200);


    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.vibrateShort({
            type: 'heavy',
            success: res => {
                console.log(res)
            }
        })

        this.data.request_type = 1
        this.data.pl_data = []
        this.data.page = 1
        this.showMessage(this.data.page)


        wx.stopPullDownRefresh();



        //消息提示刷新成功


    },



    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})